package com.wyj.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.wyj.io.Resources;
import com.wyj.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author wuyijie
 * @description: TODO xml解析类。创造者模式
 * @date 2021/10/30 10:39 上午
 */
public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * TODO: 通过dom4j解析xml，封装configuration
     *
     * @param inputStream 字节流
     * @return com.wyj.pojo.Configuration
     * @author wuyijie
     * @date 2021/10/30 10:40 上午
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document read = new SAXReader().read(inputStream);
        Element rootElement = read.getRootElement();
        //1、解析datasource配置。
        // 使用xpath进行解析
        List<Node> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Node node : list) {
            Element o = (Element) node;
            String name = o.attributeValue("name");
            String value = o.attributeValue("value");
            properties.setProperty(name, value);
        }
        //使用c3p0连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("user"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        this.configuration.setDataSource(comboPooledDataSource);

        //2、解析mapper 获取路径--获取字节流--解析dom
        List<Node> nodeList = read.selectNodes("//mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        for (Node node : nodeList) {
            Element element = (Element) node;
            // 得到mapper的路径
            String resource = element.attributeValue("value");
            // 解析mapper
            xmlMapperBuilder.parse(Resources.getResourceAsStream(resource));
        }

        return configuration;
    }

}
